package org.ceva.training.persistence.dao;

import org.ceva.training.persistence.bo.User;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.zkoss.lang.Strings;

public class UsersDAO extends HibernateDaoSupport {
	private static final Log log = LogFactory.getLog(UsersDAO.class);

	// property constants
	public static final String FIRSTNAME = "firstname";

	public static final String LASTNAME = "lastname";

	public static final String LOGINNAME = "loginname";

	public static final String PASSWORD = "password";

	public static final String USERROLE = "userrole";

	public static final String STATUS = "status";

	public static final String EMAIL = "email";

	protected void initDao() {
		// do nothing
	}
	
	public long login(User user) {
		List<User> list = findByLoginname(user.getLoginname());
		if(list.isEmpty()){
			return -1;
		}
		
		Iterator<User> it = list.iterator();
		User temp;
		while(it.hasNext()){
			temp = it.next();
			if(temp.getPassword().equals(user.getPassword())){
				return temp.getUserid();
			}
		}
		
		return -2;
	}
	/** Generate query string */ 
	public String generateQueryString(String where, String orderBy) {
		final StringBuffer sb = new StringBuffer(256);
		sb.append("FROM " + User.class.getName());
		if (!Strings.isBlank(where)) {
			sb.append(" WHERE "+where);
		}
		if (!Strings.isBlank(orderBy)) {
			sb.append(" ORDER BY "+orderBy);
		}
		return sb.toString();
	}
	public List<User> find(String queryString, int startLimit, int noOfRecords) {
		log.debug("finding all User instances");
		try {
			
			HibernateTemplate template=getHibernateTemplate();			
			int setMaxRecords = startLimit + noOfRecords + 1;
			logger.info("Set Max Result "+ setMaxRecords);
			template.setMaxResults(setMaxRecords);
			List result = template.find(queryString);
			List finalResult = new ArrayList();
			int count = result.size()-startLimit;
			if( count < noOfRecords) {
				noOfRecords = count;
			}
			int i=0;
			logger.info("Start Count "+startLimit + ".Records Accessed "+noOfRecords);
			while (noOfRecords > i) {
				logger.info("Start Count "+startLimit+i+",Rdcord "+result.get(startLimit+i));
				finalResult.add(result.get(startLimit+i));
				i++;
			}
			return finalResult;				
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	public void save(User transientInstance) {
		log.debug("saving User instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(User persistentInstance) {
		log.debug("deleting User instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}


	public void update(User persistentInstance) {
		log.debug("update User instance");
		try {
			getHibernateTemplate().update(persistentInstance);
			log.debug("update successful");
		} catch (RuntimeException re) {
			log.error("updation failed", re);
			throw re;
		}
	}
	
	
	public User findById(java.lang.Long id) {
		log.debug("getting User instance with id: " + id);
		try {
			User instance = (User) getHibernateTemplate().get(
					".database.User", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(User instance) {
		log.debug("finding User instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding User instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from User as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByFirstname(Object firstname) {
		return findByProperty(FIRSTNAME, firstname);
	}

	public List findByLastname(Object lastname) {
		return findByProperty(LASTNAME, lastname);
	}

	public List findByLoginname(Object loginname) {
		return findByProperty(LOGINNAME, loginname);
	}

	public List findByPassword(Object password) {
		return findByProperty(PASSWORD, password);
	}

	public List findByUserRole(Object userrole) {
		return findByProperty(USERROLE, userrole);
	}

	public List findByStatus(Object status) {
		return findByProperty(STATUS, status);
	}

	public List findByEmail(Object email) {
		return findByProperty(EMAIL, email);
	}

	public List findAll() {
		log.debug("finding all User instances");
		try {
			String queryString = "from User";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public User merge(User detachedInstance) {
		log.debug("merging User instance");
		try {
			User result = (User) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(User instance) {
		log.debug("attaching dirty User instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(User instance) {
		log.debug("attaching clean User instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static UsersDAO getFromApplicationContext(ApplicationContext ctx) {
		return (UsersDAO) ctx.getBean("UsersDAO");
	}
}